﻿using MediatR;
using SlaughterItem.Common.Domains.Manages;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week01.SectionCommands
{
    public class SectionShowHandler : IRequestHandler<SectionShowCommand, Result>
    {
        public IBaseRepositoryGet<Sections> sections;
        public IBaseRepositoryGet<Business> business;

        public SectionShowHandler(IBaseRepositoryGet<Sections> sections, IBaseRepositoryGet<Business> business)
        {
            this.sections = sections;
            this.business = business;
        }

        public async Task<Result> Handle(SectionShowCommand request, CancellationToken cancellationToken)
        {
            //定义返回值
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            var data = (from a in sections.GetAll()
                        join b in business.GetAll()
                        on a.BusinessId equals b.BusinessId
                        select new ShowSectionData
                        {
                             SectionId    =a.SectionId,
                             SectionName  =a.SectionName,
                             SectionType  =a.SectionType,
                             BusinessId   =a.BusinessId,
                             IsDelete     =a.IsDelete,
                             BusinessName =b.BusinessName,
                        }).ToList();
            if (!string.IsNullOrEmpty(request.SectionName))
            {
                data = data.Where(x => x.SectionName.Contains(request.SectionName)).ToList();
            }
            request.count = data.Count;
            request.znum = Math.Ceiling((request.count / request.qnum)*0.1)+1;
            data = data.OrderBy(x => x.SectionId).Skip((request.ynum - 1) * request.qnum).Take(request.qnum).ToList();
            if (data != null)
            {
                var ShowData = new { data = data, count = request.count, znum = request.znum };
                result.Data = ShowData;
                result.Code = (int)CommonErrorCode.Success;
                return result;
            }
            else
            { 
                return result;
            }
        }
    }
}
